<template>
  <div class="container">
    <div id="container-map"></div>

    <section class="container-box">
      <ZhangZiNavBar :navType="navType"></ZhangZiNavBar>
      <div class="router-view">
        <RouterView v-if="isrouterDisplay" />
      </div>
    </section>

    <div
      class="sign"
      v-if="routeLink == 'zhzf' || routeLink == 'zhyx' || routeLink == 'zhfx'"
    >
      <ul>
        <li v-for="(item, index) in userList">
          <img
            :src="require(`@assets/images/zhangzi/home/chuli${index + 1}.png`)"
            alt=""
          />
          <span>{{ item.name }}</span>
        </li>
      </ul>
    </div>
    <!-- 综合执法运行指数点位 -->
    <div class="sign" style="width: 10rem" v-if="routeLink == 'zhzfyxzs'">
      <ul>
        <li v-for="(item, index) in userList2">
          <img
            :src="require(`@assets/images/zhangzi/home/chuli${index + 1}.png`)"
            alt=""
          />
          <span>{{ item.name }}</span>
        </li>
      </ul>
    </div>
    <!-- 人员点位 -->
    <div class="personne" v-if="iserror">
      <div style="position: relative">
        <span style="margin-right: 2rem">姓名：{{ account }}</span>
        <span>片区：{{ address }}</span>
        <el-date-picker
          v-model="value1"
          format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 280px; margin-left: 1rem"
          @change="Onchangec"
        >
        </el-date-picker>
        <i class="el-icon-error" @click="onclick"></i>
      </div>
      <PersonnelMap ref="RefsPersonnelMap" :userId="userId" />
    </div>
    <!-- 监控预警 -->
    <div class="sign" v-if="routeLink == 'fxjkyj'">
      <ul>
        <li v-for="(item, index) in userList3">
          <img
            :src="require(`@/assets/images/home/chuli3.png`)"
            alt=""
          />
          <span>{{ item.name }}</span>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import ZhangZiNavBar from "@/components/ScreenNav/ZhangZiNavBar.vue"; //顶部导航
import {
  ZongHeZhiFaDB,
  ZhiNengHuaYingYongFenXi,
  ZongHeZhztaDB,
  ZhShianalysis,
  ZongHeZhiFaZhuanTi,
  ZhiNengFenxiYanPan,
  FengXianJianKong,
} from "@/api/zhangzi";
import PersonnelMap from "@/views/PersonnelMap.vue";
import Bus from "@/untils/bus";
import { dateFormat } from "@/filter/publicMethod";

let MapContainer = null;
let AMap_Center = ["112.87795", "36.12222"];
let AMap_MarkerList = [];
let AMap_HomeMarkerList = [];
let AMap_Layer = null;
let AMap_LabelMarker = [];
let heatmap = null;
let BUJIANLIST = [];
let polygons = [];
let clusterss = null;
let AMap_HeatMap = null;

export default {
  components: {
    ZhangZiNavBar,
    PersonnelMap,
  },
  data() {
    return {
      userList3: [{ name: "快超期", color: "#FFA726" }],
      value1: "",
      iserror: false,
      SwitchValue: null,
      navType: "",
      isrouterDisplay: true,
      userList: [
        {
          name: "待处理",
          color: "#E53935",
        },
        {
          name: "处理中",
          color: "#FF7043",
        },
        {
          name: "已超期",
          color: "#FFA726",
        },
      ],
      userList2: [
        {
          name: "采集正常",
          color: "#E53935",
        },
        {
          name: "采集良好",
          color: "#FF7043",
        },
        {
          name: "采集异常",
          color: "#FFA726",
        },
      ],
      routeLink: "",
      account: "",
      address: "",
      userId: "",
    };
  },

  watch: {
    // 根据路由name属性切换地图标记
    $route: {
      handler: function (route) {
        this.routeLink = "";
        this.heatmaps();

        if (AMap_LabelMarker.length) {
          AMap_Layer.remove(AMap_LabelMarker);
          MapContainer.remove(AMap_Layer);
        }
        this.$nextTick((_) => {
          MapContainer ? MapContainer.clearMap() : "";
        });
        this.$nextTick(() => {
          AMap_LabelMarker = [];
          switch (route.name) {
            // 综合执法分析
            case "zhzf":
              this.routeLink = "zhzf";
              this.disposePageFn();
              break;
            // 智能化应用分析
            case "analysis":
              this.OnlineDevices();
              break;
            case "zhsr":
              this.initCreateMap();
              break;
            // 综合运行分析 地图一样共用一个
            case "zhyx":
              this.routeLink = "zhyx";
              this.disposePageFn();
              break;
            case "zhzfyxzs":
              this.routeLink = "zhzfyxzs";
              this.disposePageFn();
              break;
            case "zfzt":
              this.NumberOfPeopleOnline();
              break;
            case "zhfx":
              this.routeLink = "zhfx";
              this.disposePageFn();
              break;
            case "znfiyp":
              this.routeLink = "";
              this.zhiNengFenxiYanPanFn();
              break;
            case "fxjkyj":
              this.routeLink = "fxjkyj";
              this.getTimeoutWarning();
              break;
            default:
              break;
          }
        });
      },
      immediate: true,
    },
  },

  mounted() {
    this.initMap();
    Bus.$on("BujianType", (data, SwitchValue) => {
      // console.log('BujianType123456', data, SwitchValue);
      this.SwitchValue = SwitchValue;
      if (SwitchValue) {
        this.initMap();
        this.disposePersonnel();
      } else {
        this.iserror = false;
        this.initMap();
        this.heatmaps();
        this.disposePageFn();
      }
    });
  },

  methods: {
    // 获取点位
    async getTimeoutWarning() {
      const { success, data, message } =
        await FengXianJianKong.getTimeoutWarningAPI();
      if (success) {
        let arr = data.map((item) => {
          return {
            lon: item.longitude,
            lat: item.latitude,
            // icon: require("@/assets/images/zhangzi/tongji/zaixian.png"),
            icon: require("@/assets/images/home/chuli3.png"),
          };
        });
        this.$nextTick((_) => {
          this.MapToMarker(arr, 26, 35);
        });
      } else {
        this.$message.error(message);
      }
    },
    onclick() {
      this.iserror = false;
    },
    Onchangec() {
      let start = dateFormat(this.value1[0]);
      let end = dateFormat(this.value1[1]);
      this.$nextTick(() => {
        this.$refs.RefsPersonnelMap.personalList(start, end);
      });
      console.log(start, end);
    },
    // 初始化地图
    initMap() {
      MapContainer = new AMap.Map("container-map", {
        mapStyle: "amap://styles/blue",
        resizeEnable: true,
        viewMode: "3D",
        pitch: 30,
        zoom: 15,
        rotation: 0,
        center: AMap_Center,
        zooms: [2, 20],
      });
    },
    heatmaps(positionList) {
      AMap.plugin("AMap.DistrictSearch", () => {
        // 创建行政区查询对象
        var district = new AMap.DistrictSearch({
          // 返回行政区边界坐标等具体信息
          extensions: "all",
          // 设置查询行政区级别为 区
          level: "district",
        });
        district.search("长子县", function (status, result) {
          var bounds = result.districtList[0].boundaries;
          let polygon = null;
          if (bounds) {
            //生成行政区划polygon
            for (var i = 0; i < bounds.length; i += 1) {
              //构造MultiPolygon的path
              bounds[i] = [bounds[i]];
            }
            polygon = new AMap.Polygon({
              strokeWeight: 1,
              path: bounds,
              fillOpacity: 0.4,
              fillColor: "transparent",
              strokeColor: "#0091ea",
            });
            MapContainer.add(polygon);
            MapContainer.setFitView(polygon); //视口自适应
          }
        });
      });
    },
    //销毁
    removeLine(arr) {
      MapContainer ? MapContainer.remove(arr) : "";
    },
    /**
     * 综合执法地图点位
     */
    disposePageFn() {
      // this.heatmaps()
      ZongHeZhiFaDB.disposePage().then((res) => {
        // console.log(res, '综合执法地图点位');
        if (res.code == 200) {
          let list = [];
          res.data.forEach((element) => {
            // console.log(element.state,'element.state');
            if (element.lat && element.lon) {
              list.push({
                lon: element.lon,
                lat: element.lat,
                id: element.id,
                status: element.state,
                icon: {
                  image: require(`@/assets/images/zhangzi/home/chuli${Number(
                    element.state
                  )}.png`),
                  type: "image",
                  size: [23, 32],
                  anchor: "bottom-center",
                },
              });
            }
          });
          this.$nextTick(() => {
            this.listMarkerCluster(list);
          });
        }
      });
    },

    /**
     * 综合执法分析增加人员定位和轨迹图
     */
    async disposePersonnel() {
      this.heatmaps();
      const res = await ZongHeZhiFaDB.trajectory();
      console.log(res, "综合执法分析增加人员定位和轨迹图");
      if (res.code == 200) {
        let list = [];
        let ele = {};
        res.data.forEach((element) => {
          if (element.coordinate) {
            ele = element.coordinate.split(",");
          }
          list.push({
            lon: ele[0],
            lat: ele[1],
            icon: {
              image: require(`@/assets/images/zhangzi/zhifazhuanti/zaixian.png`),
              size: [23, 32],
            },
            userId: element.id,
            account: element.account,
            address: element.address,
            sum: element.sum,
          });
        });
        console.log(list, "综合执法分析增加人员定位和轨迹图");
        this.$nextTick(() => {
          this.listMarkerCluster(list);
        });
      }
    },

    /**
     * 智能化应用分析地图点位
     */
    async OnlineDevices() {
      const res = await ZhiNengHuaYingYongFenXi.mapOnlineDevicesAPI();
      if (res.success) {
        let arr = res.data.map((item) => {
          // 1不在线  0在线
          if (item.isOnlone == 1) {
            return {
              lon: item.longitude,
              lat: item.latitude,
              icon: require("@/assets/images/zhangzi/tongji/lixian.png"),
            };
          } else {
            return {
              lon: item.longitude,
              lat: item.latitude,
              icon: require("@/assets/images/zhangzi/tongji/zaixian.png"),
            };
          }
        });
        this.$nextTick((_) => {
          this.MapToMarker(arr);
        });
      } else {
        this.$message.error(res.message);
      }
    },

    /**
     * 自定义点标记
     * @param {Array} list { lon:number,lat:number,icon:string }
     */
    MapToMarker(list, w, h) {
      let markerList = [];
      list.forEach((item) => {
        // 创建一个 Icon
        let marker = new AMap.Marker({
          position: new AMap.LngLat(item.lon, item.lat),
          icon: new AMap.Icon({
            // 图标尺寸
            size: new AMap.Size(w ? w : 26, h ? h : 32),
            // 图标的取图地址
            image: item.icon,
            // 图标所用图片大小
            imageSize: new AMap.Size(w ? w : 26, h ? h : 32),
          }),
        });
        // marker.setMap(null);
        // marker = null
        markerList.push(marker);
      });
      MapContainer.add(markerList);
      MapContainer.setFitView();
    },

    // 窗体
    mapListker(list) {
      let arr = [];
      for (let i = 0; i < list.length; i++) {
        let content = `<div style="padding: .5rem 0  0 .625rem; width: 7.5625rem;height:3.375rem;
                border: .0625rem solid #F33635; border-right:.1875rem solid #F33635;" >
                <p style="font-size: .875rem;
                margin-bottom: .1875rem;
                color: #FFFFFF;">高发道路</p>
                <p style="font-size: .875rem;
                color: #FFFFFF;">道路名称${list[i].name}</p></div>`;
        var position = new AMap.LngLat(list[i].lon, list[i].lat);
        var marker = new AMap.Marker({
          position: position,
          // 将 html 传给 content
          content: content,
          // 以 icon 的 [center bottom] 为原点
          offset: new AMap.Pixel(-103, 2),
        });
        arr.push(marker);
        MapContainer.add(arr);
        MapContainer.setFitView();
      }
    },
    /**
     * 海量点位台添加
     * @param {点位数组, lon: 经度， lat：纬度，icon： 图标 } list
     */
    listMarkerCluster(list) {
      var curData = {};
      AMap_LabelMarker = [];
      AMap_Layer = new AMap.LabelsLayer({
        zooms: [2, 20],
        zIndex: 10000,
        collision: false,
      });
      list.forEach((item) => {
        curData = {
          // name: item.userId,
          position: [item.lon, item.lat],
          icon: item.icon,
        };
        var labelMarker = new AMap.LabelMarker(curData);

        labelMarker.setExtData(item);
        labelMarker.on("click", (e) => {
          // if (e.target.getExtData().userId && e.target.getExtData().sum == '0') return this.$message.info('当前暂无轨迹')
          if (
            e.target.getExtData().userId &&
            e.target.getExtData().sum != "0"
          ) {
            this.account = e.target.getExtData().account;
            this.address = e.target.getExtData().address;
            this.userId = e.target.getExtData().userId;
            this.iserror = true;
            this.$nextTick(() => {
              this.$refs.RefsPersonnelMap.personalList();
            });
            console.log(this.userId, "userId");
            console.log(e.target.getExtData());
          }
        });
        AMap_LabelMarker.push(labelMarker);
      });
      AMap_Layer.add(AMap_LabelMarker);
      MapContainer.add(AMap_Layer);
    },
    // 环卫 地图
    initCreateMap() {
      // this.heatmaps()
      ZongHeZhztaDB.getPoint().then((res) => {
        // console.log(res, '地图');
        if (res.code == 200) {
          let list = res.data.map((item) => {
            return {
              name: item.name,
              lon: item.lon,
              lat: item.lat,
              icon: require("@/assets/images/zhangzi/Sanitation/icon2.png"),
            };
          });
          this.$nextTick(() => {
            this.MapToMarker(list, 119, 140);
            this.mapListker(list);
          });
        }
      });
    },

    /**
     * 综合执法专题大地图点位
     */
    async NumberOfPeopleOnline() {
      // this.heatmaps()
      const { success, data, message } =
        await ZongHeZhiFaZhuanTi.NumberOfPeopleOnlineMap();
      if (success) {
        // console.log(data);
        // { lon:number,lat:number,icon:string }
        // 1不在线  0在线
        let arr = data.map((e) => {
          return {
            lon: e.lon,
            lat: e.lat,
            icon:
              e.isOnline == "否"
                ? require("@/assets/images/zhangzi/zhifazhuanti/lixian.png")
                : require("@/assets/images/zhangzi/zhifazhuanti/zaixian.png"),
          };
        });
        this.$nextTick((_) => {
          this.MapToMarker(arr, 40, 48);
        });
      } else {
        this.$message.error(message);
      }
    },

    /**
     * 智能分析研判
     */
    async zhiNengFenxiYanPanFn() {
      const { success, data, message } =
        await ZhiNengFenxiYanPan.ticketMapHotIssueDB();
      if (success) {
        console.log(data, "zhiNengFenxiYanPanFn");
        let arr = data.map((e) => {
          return {
            lon: e.lon,
            lat: e.lat,
            icon: require("@/assets/images/zhangzi/zhifazhuanti/lixian.png"),
          };
        });
        this.$nextTick((_) => {
          this.MapToMarker(arr, 40, 48);
        });
      } else {
        this.$message.error(message);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
}

#container-map {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 100;
}

.router-view {
  position: relative;
  top: 7.3125rem;
  height: auto;
}

.sign {
  width: 9.5rem;
  background: url("../assets/images/zhangzi/home/chili-bg.png") no-repeat;
  background-size: 100% 100%;
  padding: 1.25rem 1rem;
  position: absolute;
  bottom: 4rem;
  right: 55.375rem;
  z-index: 100;

  ul {
    width: 100%;
    margin: 0;

    li {
      display: flex;
      align-items: center;
      margin-bottom: 1rem;

      &:last-child {
        margin: 0;
      }

      img {
        width: 1.4375rem;
        height: 2rem;
      }

      span {
        display: inline-block;
        margin-left: 1rem;
        font-size: 1.375rem;
        font-family: Adobe Heiti Std;
        color: #ffffff;
      }
    }
  }
}

.personne {
  padding: 2rem;
  position: fixed;
  left: 50%;
  top: 45%;
  width: 65.6rem;
  height: 440px;
  transform: translate(-50%, -50%);
  background-color: #112d53;
  z-index: 1000;
  color: #fff;
}

/deep/ .el-icon-error:before {
  position: absolute;
  right: 0;
  top: 0;
  font-size: 20.5rem;
}
</style>